package cn.bdqn.service.impl;

import cn.bdqn.dao.ProductDao;
import cn.bdqn.entity.Product;
import cn.bdqn.enums.JxcEnum;
import cn.bdqn.exception.JxcException;
import cn.bdqn.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 郑大仙丶
 * @date 2018-12-31 13:33
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;


    // 查询全部的商品
    @Override
    public List<Product> findAll() {
        return productDao.findAll();
    }

    // 减少库存.
    @Override
    @Transactional
    public void decreaseQuantity(Integer id, Integer saleQuantity) {
        //1. 查询商品库存
        Integer productQuantity = this.findQuantityById(id);
        //2. 判断商品的销售量是否大于商品的库存数.
        if(saleQuantity > productQuantity){
            // 商品库存不足.
            throw new JxcException(JxcEnum.PRODUCT_QUANTITY_NOT_ENOUGH);
        }
        //3. 减少商品的库存.
        Integer count = productDao.updateQuantityById(saleQuantity, id);
        //4. 减少库存是否成功.
        if(count != 1){
            throw new JxcException(JxcEnum.PRODUCT_QUANTITY_UPDATE_ERROR);
        }
    }

    // 查询商品库存
    @Override
    public Integer findQuantityById(Integer id) {
        //1. 查询库存数.
        Integer quantity = productDao.findQuantityById(id);
        //2. 判断库存数
        if(quantity == null || quantity < 0){
            // 抛出异常.
            throw new JxcException(JxcEnum.PRODUCT_QUANTITY_ERROR);
        }
        //3. 返回库存数
        return quantity;
    }
}
